package com.app.community.service;

import com.app.community.dto.CommentDTO;
import com.app.community.dto.LeaderBoardDTO;
import com.app.community.dto.PosterDTO;
import com.app.community.mapper.CommentMapper;
import com.app.community.model.entity.Comment;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评论业务逻辑
 * 2020/10/27 19:41
 **/
@Service
public class CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    NotificationService notificationService;

    public List<CommentDTO> selectComment(Long questionId) {
        return commentMapper.selectComment(questionId);
    }

    public void publishComment(String userId, String comment, String date, Long questionId) {
        commentMapper.publishComment(userId, comment, date, questionId);
        notificationService.insertCommentNotification(questionId,userId);
    }

    public Integer selectCommentNum(Long questionId) {
        return commentMapper.selectCommentNum(questionId);
    }

    @Cacheable(cacheNames = "OneWeekUserLeaderBoard")
    public List<LeaderBoardDTO> selectOneWeekUserLeaderBoard() {
        // 根据评论数量计算排名,返回排名倒序
        List<LeaderBoardDTO> leaderBoardDTOS = commentMapper.selectOneWeekUserLeaderBoard().stream().sorted(Comparator.comparing(LeaderBoardDTO::getCommentNum)).collect(Collectors.toList());

        List<LeaderBoardDTO> results = new ArrayList<>();
        // 取最后三个昵称
        for (int i = leaderBoardDTOS.size() - 1; i > leaderBoardDTOS.size() - 4 && i >= 0; i--) {
            results.add(leaderBoardDTOS.get(i));
        }

        return results;
    }

    @Cacheable(cacheNames = "OneWeekPoster")
    public List<PosterDTO> selectOneWeekPoster(){
        List<PosterDTO> posterDTOS = commentMapper.selectOneWeekPoster().stream().sorted(Comparator.comparing(PosterDTO::getCommentNum)).collect(Collectors.toList());

        List<PosterDTO> results = new ArrayList<>();
        for (int i = posterDTOS.size() - 1; i >posterDTOS.size() - 4 && i >= 0; i--) {
            results.add(posterDTOS.get(i));
        }
        return results;
    }

}
